package cn.dubito.o2o.utils;

import cn.dubito.o2o.exception.ShopOperationException;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Position;
import net.coobird.thumbnailator.geometry.Positions;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @author liliang
 * @description:
 * @date 2018/4/18.
 */
public class ImageUtil {

    /**
     * 时间格式化格式
     */
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
    private static final Random RANDOM = new Random();

    private static final String BASE_PATH = Thread.currentThread().getContextClassLoader().getResource("").getPath();

    public static String generateThumbnail(MultipartFile thumbnail, String targetPath) {
        String realFileName = getRandomFileName();
        String extension = getFileExtension(thumbnail);
        makeDirPath(targetPath);
        String relativePath = targetPath + realFileName + extension;
        File file = new File(PathUtil.getImageBasePath() + relativePath);
        // 添加水印
        try {
            BufferedImage image = ImageIO.read(thumbnail.getInputStream());
            BufferedImage waterImage = ImageIO.read(new File(BASE_PATH + "/sy.png"));
            // 随机位置添加水印
            Thumbnails.of(thumbnail.getInputStream()).size(image.getWidth(), image.getHeight())
                    .watermark((i, i1, i2, i3, i4, i5, i6, i7) -> new Point(new Random()
                                    .nextInt(image.getWidth() - waterImage.getWidth()),
                                    new Random().nextInt(image.getHeight() - waterImage.getHeight())),
                            waterImage
                            , 0.25f)
                    .outputQuality(0.8f).toFile(file);
        } catch (IOException e) {
            throw new ShopOperationException("图片处理异常");
        }
        return relativePath;
    }

    /**
     * 创建目标路径所涉及的目录 /home/dubito/image/targetPath/XXX/XXX.jpg
     * 不存在自动创建
     *
     * @param targetPath
     */
    private static void makeDirPath(String targetPath) {
        String realFileParentPath = PathUtil.getImageBasePath() + targetPath;
        File dir = new File(realFileParentPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    /**
     * 获取文件扩展名
     *
     * @param thumbnail
     * @return
     */
    private static String getFileExtension(MultipartFile thumbnail) {
        String originalFileName = thumbnail.getOriginalFilename();
        return originalFileName.substring(originalFileName.lastIndexOf("."));
    }

    /**
     * 生成随机文件名,当前年月日时分秒+五位随机数
     *
     * @return
     */
    private synchronized static String getRandomFileName() {
        int randomInt = RANDOM.nextInt(89999) + 10000;
        String nowTimeStr = DATE_FORMAT.format(new Date());
        return nowTimeStr + randomInt;
    }


    /**
     * storePath是文件的路径还是目录的路径
     * 如果是目录则删除目录下的所有文件
     *
     * @param storePath
     */
    public static void deleteFileOrPath(String storePath) {
        File fileOrPath = new File(PathUtil.getImageBasePath() + storePath);
        if (fileOrPath.exists()) {
            if (fileOrPath.isDirectory()) {
                File[] files = fileOrPath.listFiles();
                if (files != null) {
                    for (File file : files) {
                        file.delete();
                    }
                }
            }
            fileOrPath.delete();
        }
    }

    public static void main(String[] args) throws IOException {
        Thumbnails.of(new File("/Users/liliang/Downloads/412.jpg"))
                .size(800, 800)
                .watermark(Positions.BOTTOM_RIGHT,
                        ImageIO.read(new File(BASE_PATH + "/sy.png")), 0.25f)
                .outputQuality(0.8f)
                .toFile("/Users/liliang/Downloads/412new.jpg");

        makeDirPath("/hha");
    }


}
